from elasticsearch import Elasticsearch

es = Elasticsearch()


# 创建索引

def create_index(name):
    ret = es.indices.create(index=name, body={
        "mappings": {
            "properties": {
                "title": {  # title是电影名
                    "type": "text",
                    "analyzer": "ik_max_word",
                },
                "link": {  # 链接
                    "type": "text",
                    "analyzer": "ik_max_word",
                },
                # "From": {  # 来源
                #     "type": "text",
                #     "analyzer": "ik_max_word",
                # },
                "score": {  # 评分
                    "type": "text",
                    "analyzer": "ik_max_word",
                },
                "detailed": {  # 简介
                    "type": "text",
                    "analyzer": "ik_max_word",
                },
                "img": {  # 图片
                    "type": "text",
                    "analyzer": "ik_max_word",
                },
                "actor": {  # 演员
                    "type": "text",
                    "analyzer": "ik_max_word",
                },
                "pingjia": {  # 演员
                    "type": "text",
                    "analyzer": "ik_max_word",
                }
            }
        }
    })
    print(ret)
    return ret


# ----------------------向索引里面插入数据-----------------------
def insert_index(name, id, body):
    ret = es.create(index=name, doc_type='_doc', id=id, body=body)
    print(ret)
    return ret


# -------------------------查询--------------------------------

def search1(name, value):
    """
    全文检索
    :param name:
    :param value:
    :return:
    """
    ret = es.search(index=name, doc_type='_doc', body={
        'query': {
            'multi_match': {
                'query': value,
                'fields': ['title', 'score','detailed','actor']
            }
        }
    })
    ret = ret['hits']['hits']
    ret_new = []
    if ret:
        for art in ret:
            ret_new.append(art['_source'])
    for art in ret_new:
        print('电影名称：' + str(art['title']))
        print('评分：' + str(art['score']))
        # print('评分：' + str(art['move_jianjie']))
    return ret_new

